<template>
  <div class="table-page">
    <div class="flex flex-a-c flex-wrap">
      <div class="h-10n flex-center text-size-16 font-bold px-12 bgFCEDF0 mr-20 round-6 mb-20">
        用户总数： {{ userCount.userCount }}
      </div>
      <!-- <div class="h-10n flex-center text-size-16 font-bold px-12 bgFCEDF0 mr-20 round-6 mb-20">
        团队总数： {{ userCount.teamCount }}
      </div> -->
      <div class="h-10n flex-center text-size-16 font-bold px-12 bgFCEDF0 mr-20 round-6 mb-20">
        今日新增注册： <span class="text43cf7c">{{ userCount.todayAddCount }}</span>
      </div>
    </div>
    <a-form label-align="right" layout="inline" auto-label-width :model="listParams" size="small" class="form">
      <a-form-item field="keyword" label="关键字检索" show-colon>
        <a-input-group>
          <a-select v-model="searchKey" placeholder="选择关键字" style="width: 200px">
            <a-option value="nickname">用户昵称</a-option>
            <a-option value="mobile">手机号</a-option>
            <a-option value="inviteCode">邀请码</a-option>
            <a-option value="inviteStudentId">邀请人</a-option>
            <a-option value="tbGrandRid">淘宝授权Rid</a-option>
            <a-option value="tbUserNick">淘宝授权昵称</a-option>
            <a-option value="pddGrandPid">拼多多授权Pid</a-option>
          </a-select>
          <a-input placeholder="请输入" v-model="searchValue" :disabled="!searchKey" @press-enter="changeCurrent(1)" />
        </a-input-group>
      </a-form-item>
      <a-form-item field="level" label="用户等级" show-colon>
        <a-select multiple placeholder="选择会员等级" style="width: 200px" @change="onRankId">
          <a-option :value="1">用户</a-option>
          <a-option :value="2">会员</a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="createTimeStart" label="注册时间" show-colon>
        <ms-date
          v-model:start="listParams.createTimeStart"
          v-model:end="listParams.createTimeEnd"
          @dateChange="changeCurrent(1)"
        ></ms-date>
      </a-form-item>
      <a-form-item label="是否注销" field="isDisable" show-colon>
        <a-checkbox-group v-model="checkbox1" @change="onCheckboxChange($event, 'isDisable')">
          <a-checkbox :value="1"></a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item label="是否有效" field="isValid" show-colon>
        <a-checkbox-group v-model="checkbox2" @change="onCheckboxChange($event, 'isValid')">
          <a-checkbox :value="1"></a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item label="邀请有效会员数" field="invitedNum" show-colon>
        <a-input-group compact>
          <a-input-number v-model="listParams.invitedNum.min" :min="0" class="w-30n" placeholder="最少会员数" />
          <a-input style="width: 40px; pointer-events: none" placeholder="~" disabled />
          <a-input-number v-model="listParams.invitedNum.max" :min="1" class="w-30n" placeholder="最多会员数" />
        </a-input-group>
      </a-form-item>
      <a-form-item label="订单数量" field="invitedNum" show-colon>
        <a-input-group compact>
          <a-select v-model="orderType" class="w-30n">
            <a-option value="orderNum"> 订单总数 </a-option>
            <a-option value="orderValidNum"> 有效订单数 </a-option>
          </a-select>
          <a-input-number v-model="orderMin" :min="0" class="w-30n" placeholder="最小数量" />
          <a-input style="width: 40px; pointer-events: none" placeholder="~" disabled />
          <a-input-number v-model="orderMax" :min="1" class="w-30n" placeholder="最大数量" />
        </a-input-group>
      </a-form-item>
      <a-form-item>
        <a-space class="flex-center">
          <a-button type="primary" size="small" @click="changeCurrent(1)">
            <template #icon>
              <icon-search />
            </template>
            <template #default>查询</template>
          </a-button>
          <a-button size="small" @click="onResetSearch">
            <template #icon>
              <icon-sync />
            </template>
            <template #default>重置</template>
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <GiTable
      row-key="id"
      id="userList66786"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      @refresh="getTableData"
    >
      <template #isValid="{ record }">
        <div v-if="record.isValid == 1" class="flex flex-a-c" style="color: #1bae57">
          <icon-check-circle size="20px" /> 有效
        </div>
        <div v-else class="flex flex-a-c" style="color: #333"><icon-close-circle size="20px" /> 无效</div>
      </template>
      <template #inviteId="{ record, rowIndex }">
        <a-popover title="邀请人信息" trigger="click" v-if="record.inviteId">
          <a-link status="warning" @click="getInfo(record.inviteId)">{{ record.inviteId }}</a-link>
          <template #content>
            <a-descriptions style="width: 600px" v-if="userDetailInfo">
              <a-descriptions-item label="邀请码">
                {{ record.inviteId }}
              </a-descriptions-item>
              <a-descriptions-item label="手机号">{{ userDetailInfo.mobile || '--' }}</a-descriptions-item>
              <a-descriptions-item label="注册时间">{{ userDetailInfo.registerAt || '--' }}</a-descriptions-item>
              <a-descriptions-item label="微信">{{ userDetailInfo.wx || '--' }}</a-descriptions-item>
            </a-descriptions>
            <div v-else style="display: flex; justify-content: center; width: 100%">
              <a-spin />
            </div>
          </template>
        </a-popover>
        <div v-else>--</div>
      </template>
      <template #invitePid="{ record }">
        <a-popover title="渠道方信息" trigger="click" v-if="record.invitePid">
          <a-link status="warning" @click="getInfo(record.invitePid)">{{ record.invitePid }}</a-link>
          <template #content>
            <a-descriptions style="width: 600px" v-if="userDetailInfo">
              <a-descriptions-item label="邀请码">
                {{ record.invitePid }}
              </a-descriptions-item>
              <a-descriptions-item label="手机号">{{ userDetailInfo.mobile || '--' }}</a-descriptions-item>
              <a-descriptions-item label="注册时间">{{ userDetailInfo.registerAt || '--' }}</a-descriptions-item>
              <a-descriptions-item label="微信">{{ userDetailInfo.wx || '--' }}</a-descriptions-item>
            </a-descriptions>
            <div v-else style="display: flex; justify-content: center; width: 100%">
              <a-spin />
            </div>
          </template>
        </a-popover>
        <div v-else>--</div>
      </template>
      <template #inviteNum="{ record }">
        <div class="flex-col">
          <span>有效：{{ record.invitePartnerOrderedQuantity }}</span>
          <span>总数：{{ record.invitePartnerAllNum }}</span>
        </div>
      </template>
      <template #day="{ record }">
        <div class="flex-col">
          <span>余：{{ record.remainingEquityDay }}天</span>
          <span>总：{{ record.accumulatedEquityDay }}天</span>
        </div>
      </template>
      <template #action="{ record }">
        <a-button type="text" size="small" @click="onAddOrEdit(record)"> 查看详情 </a-button>
      </template>
    </GiTable>
  </div>
</template>

<script setup>
import { usePagination } from '@/hooks'
import { userAgentList, userAgentDetail, userAgentCountDetail } from '@/apis'
import MsCopyDiv from '@/components/MsCopyDiv/index.vue'
import { reAssign } from '@/utils/common'
import { deepClone } from '@/utils/common'
import Popover from '@/components/Popover/index.vue'
defineOptions({ name: 'userList' })
const router = useRouter()
const orderUpdateAt = ref()
const columns = ref([
  {
    title: '用户',
    width: 120,
    align: 'center',
    render: (data) => {
      const text = data.record.nickname
      return text || '--'
    }
  },
  {
    title: '级别',
    width: 100,
    align: 'center',
    render: (data) => {
      const text = data.record.userRankName
      return text || '用户'
    }
  },
  {
    title: '是否有效',
    width: 90,
    align: 'center',
    slotName: 'isValid'
  },
  {
    title: '邀请码',
    width: 150,
    align: 'center',
    render: (data) => {
      const text = data.record.inviteCode
      return h(MsCopyDiv, { text, title: '邀请码', line: 1 })
    }
  },
  {
    title: '手机号',
    width: 150,
    align: 'center',
    render: (data) => {
      const text = data.record.mobile
      return text || '--'
    }
  },
  {
    title: '邀请人',
    width: 120,
    align: 'center',
    slotName: 'inviteId'
  },
  {
    title: '渠道方',
    width: 150,
    align: 'center',
    slotName: 'invitePid'
  },
  {
    title: '总订单数',
    dataIndex: 'orderNum',
    align: 'center',
    width: 150,
    filterable: {
      alignLeft: true,
      slotName: 'orderNum',
      icon: () =>
        h(Popover, {
          content: `最后更新时间:\n${orderUpdateAt.value || '--'}`
        })
    }
  },
  {
    title: '有效订单数',
    dataIndex: 'orderValidNum',
    align: 'center',
    width: 150,
    filterable: {
      alignLeft: true,
      slotName: 'orderValidNum',
      icon: () =>
        h(Popover, {
          content: `最后更新时间:\n${orderUpdateAt.value || '--'}`
        })
    }
  },
  {
    title: '邀请伙伴',
    width: 150,
    align: 'center',
    slotName: 'inviteNum'
  },
  {
    title: '注册时间',
    width: 180,
    align: 'center',
    render: (data) => {
      const text = data.record.registerAt
      return text || '--'
    }
  },
  {
    title: '解锁VIP时间',
    width: 180,
    align: 'center',
    render: (data) => {
      const text = data.record.upgradeAt
      return text || '--'
    }
  },
  {
    title: '操作',
    width: 200,
    align: 'center',
    slotName: 'action',
    fixed: 'right'
  }
])

const loading = ref(false)
const tableData = ref([])
const searchKey = ref('inviteCode')
const searchValue = ref('')
const checkbox1 = ref([])
const checkbox2 = ref([])
const userDetailInfo = ref({})
const orderType = ref('orderNum')
const orderMin = ref()
const orderMax = ref()

const userCount = reactive({
  teamCount: 0,
  todayAddCount: 0,
  userCount: 0
})

const listParams = reactive({
  page: 1,
  pageSize: 10,
  level: undefined,
  isDisable: undefined,
  isValid: undefined,
  createTimeStart: undefined,
  createTimeEnd: undefined,
  channelId: undefined,
  invitedNum: {
    min: undefined,
    max: undefined
  }
})
const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: listParams.pageSize })
const getUserCount = async () => {
  const res = await userAgentCountDetail()
  reAssign(userCount, res.data)
}

// 获取列表数据
const getTableData = async () => {
  try {
    loading.value = true
    listParams.page = pagination.current
    listParams.pageSize = pagination.pageSize
    const params = deepClone(listParams)
    params[searchKey.value] = searchValue.value
    if (orderMax.value || orderMin.value) {
      params[orderType.value] = {
        min: orderMin.value || undefined,
        max: orderMax.value || undefined
      }
    } else {
      params.orderNum = params.orderValidNum = undefined
    }
    const res = await userAgentList({
      ...params,
      invitedNum: JSON.stringify(listParams.invitedNum) == '{}' ? undefined : listParams.invitedNum
    })
    tableData.value = res.data.list
    orderUpdateAt.value = tableData.value?.[0]?.orderUpdateAt
    getUserCount()
    setTotal(res?.data?.count)
  } finally {
    loading.value = false
  }
}
getTableData()
const getInfo = async (inviteCode) => {
  userDetailInfo.value = null
  const res = await userAgentDetail({ inviteCode })
  userDetailInfo.value = res.data
}
// // 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}

// 添加/编辑
const onAddOrEdit = (item) => {
  router.push({
    path: '/userChannel/userDetail',
    query: {
      id: item.id,
      iId: item.inviteCode
    }
  })
}

const onCheckboxChange = (p1, p2) => {
  listParams[p2] = p1[0] === 1 ? 1 : 0
  changeCurrent(1)
}

// 重置筛选查询
const onResetSearch = () => {
  reAssign(listParams, false)
  listParams.invitedNum = {
    min: undefined,
    max: undefined
  }
  orderType.value = 'orderNum'
  orderMin.value = undefined
  orderMax.value = undefined
  searchKey.value = 'inviteCode'
  searchValue.value = checkbox1.value = checkbox2.value = undefined
  nextTick(() => {
    changeCurrent(1)
  })
}

const onRankId = (e) => {
  if (e.length > 1 || e.length == 0) listParams.level = undefined
  else listParams.level = e[0]
  changeCurrent(1)
}
</script>

<style lang="scss" scoped>
:deep(.arco-radio-group .arco-radio) {
  margin-right: 10px;
}
.bgFCEDF0 {
  background: #fcedf0;
}
</style>
